#!/bin/bash

# 项目集进度管理系统 Docker 启动脚本
# 用于快速启动整个系统的 Docker 容器

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查 Docker 和 Docker Compose
check_docker() {
    log_info "检查 Docker 环境..."
    
    if ! command -v docker &> /dev/null; then
        log_error "Docker 未安装，请先安装 Docker"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
        log_error "Docker Compose 未安装，请先安装 Docker Compose"
        exit 1
    fi
    
    if ! docker info &> /dev/null; then
        log_error "Docker 服务未启动，请启动 Docker 服务"
        exit 1
    fi
    
    log_success "Docker 环境检查通过"
}

# 检查环境变量文件
check_env_file() {
    log_info "检查环境变量配置..."
    
    if [ ! -f ".env" ]; then
        if [ -f ".env.docker" ]; then
            log_warning "未找到 .env 文件，使用 .env.docker 作为模板"
            cp .env.docker .env
            log_info "已创建 .env 文件，请根据需要修改配置"
        else
            log_error "未找到环境变量配置文件，请创建 .env 文件"
            exit 1
        fi
    fi
    
    log_success "环境变量配置检查通过"
}

# 创建必要的目录
create_directories() {
    log_info "创建必要的目录..."
    
    directories=(
        "logs/mysql"
        "logs/redis"
        "logs/backend"
        "logs/frontend"
        "logs/nginx"
        "uploads"
        "backups"
        "docker/nginx/ssl"
    )
    
    for dir in "${directories[@]}"; do
        if [ ! -d "$dir" ]; then
            mkdir -p "$dir"
            log_info "创建目录: $dir"
        fi
    done
    
    log_success "目录创建完成"
}

# 构建镜像
build_images() {
    log_info "构建 Docker 镜像..."
    
    if command -v docker-compose &> /dev/null; then
        docker-compose build --no-cache
    else
        docker compose build --no-cache
    fi
    
    log_success "镜像构建完成"
}

# 启动服务
start_services() {
    local profile="$1"
    
    log_info "启动服务..."
    
    if [ -n "$profile" ]; then
        log_info "使用配置文件: $profile"
        if command -v docker-compose &> /dev/null; then
            docker-compose --profile "$profile" up -d
        else
            docker compose --profile "$profile" up -d
        fi
    else
        if command -v docker-compose &> /dev/null; then
            docker-compose up -d
        else
            docker compose up -d
        fi
    fi
    
    log_success "服务启动完成"
}

# 等待服务就绪
wait_for_services() {
    log_info "等待服务就绪..."
    
    # 等待数据库就绪
    log_info "等待 MySQL 数据库启动..."
    timeout=60
    while [ $timeout -gt 0 ]; do
        if docker exec project_management_mysql mysqladmin ping -h localhost --silent; then
            log_success "MySQL 数据库已就绪"
            break
        fi
        sleep 2
        timeout=$((timeout-2))
    done
    
    if [ $timeout -le 0 ]; then
        log_error "MySQL 数据库启动超时"
        return 1
    fi
    
    # 等待 Redis 就绪
    log_info "等待 Redis 缓存启动..."
    timeout=30
    while [ $timeout -gt 0 ]; do
        if docker exec project_management_redis redis-cli ping | grep -q PONG; then
            log_success "Redis 缓存已就绪"
            break
        fi
        sleep 2
        timeout=$((timeout-2))
    done
    
    if [ $timeout -le 0 ]; then
        log_error "Redis 缓存启动超时"
        return 1
    fi
    
    # 等待后端服务就绪
    log_info "等待后端服务启动..."
    timeout=60
    while [ $timeout -gt 0 ]; do
        if curl -f http://localhost:8000/health &> /dev/null; then
            log_success "后端服务已就绪"
            break
        fi
        sleep 3
        timeout=$((timeout-3))
    done
    
    if [ $timeout -le 0 ]; then
        log_warning "后端服务启动超时，请检查日志"
    fi
    
    # 等待前端服务就绪
    log_info "等待前端服务启动..."
    timeout=60
    while [ $timeout -gt 0 ]; do
        if curl -f http://localhost:8080 &> /dev/null; then
            log_success "前端服务已就绪"
            break
        fi
        sleep 3
        timeout=$((timeout-3))
    done
    
    if [ $timeout -le 0 ]; then
        log_warning "前端服务启动超时，请检查日志"
    fi
}

# 显示服务状态
show_status() {
    log_info "服务状态:"
    
    if command -v docker-compose &> /dev/null; then
        docker-compose ps
    else
        docker compose ps
    fi
}

# 显示访问信息
show_access_info() {
    echo
    log_success "=== 项目集进度管理系统启动完成 ==="
    echo
    echo "🌐 前端访问地址:"
    echo "   http://localhost:8080"
    echo
    echo "🔧 后端 API 地址:"
    echo "   http://localhost:8000"
    echo "   API 文档: http://localhost:8000/docs"
    echo
    echo "🗄️  数据库管理工具:"
    echo "   phpMyAdmin: http://localhost:8081"
    echo "   Adminer: http://localhost:8082"
    echo
    echo "📊 Redis 管理工具:"
    echo "   Redis Commander: http://localhost:8083"
    echo
    echo "📋 默认登录信息:"
    echo "   用户名: admin"
    echo "   密码: admin123"
    echo
    echo "📝 查看日志命令:"
    if command -v docker-compose &> /dev/null; then
        echo "   docker-compose logs -f [service_name]"
    else
        echo "   docker compose logs -f [service_name]"
    fi
    echo
    echo "🛑 停止服务命令:"
    if command -v docker-compose &> /dev/null; then
        echo "   docker-compose down"
    else
        echo "   docker compose down"
    fi
    echo
}

# 主函数
main() {
    local action="${1:-start}"
    local profile="$2"
    
    case "$action" in
        "start")
            log_info "启动项目集进度管理系统..."
            check_docker
            check_env_file
            create_directories
            build_images
            start_services "$profile"
            wait_for_services
            show_status
            show_access_info
            ;;
        "stop")
            log_info "停止项目集进度管理系统..."
            if command -v docker-compose &> /dev/null; then
                docker-compose down
            else
                docker compose down
            fi
            log_success "系统已停止"
            ;;
        "restart")
            log_info "重启项目集进度管理系统..."
            $0 stop
            sleep 3
            $0 start "$profile"
            ;;
        "status")
            show_status
            ;;
        "logs")
            local service="$profile"
            if [ -n "$service" ]; then
                if command -v docker-compose &> /dev/null; then
                    docker-compose logs -f "$service"
                else
                    docker compose logs -f "$service"
                fi
            else
                if command -v docker-compose &> /dev/null; then
                    docker-compose logs -f
                else
                    docker compose logs -f
                fi
            fi
            ;;
        "build")
            log_info "重新构建镜像..."
            check_docker
            build_images
            ;;
        "clean")
            log_info "清理 Docker 资源..."
            if command -v docker-compose &> /dev/null; then
                docker-compose down -v --rmi all
            else
                docker compose down -v --rmi all
            fi
            docker system prune -f
            log_success "清理完成"
            ;;
        "help")
            echo "用法: $0 [命令] [选项]"
            echo
            echo "命令:"
            echo "  start [profile]  启动系统 (默认)"
            echo "  stop            停止系统"
            echo "  restart [profile] 重启系统"
            echo "  status          查看服务状态"
            echo "  logs [service]  查看日志"
            echo "  build           重新构建镜像"
            echo "  clean           清理 Docker 资源"
            echo "  help            显示帮助信息"
            echo
            echo "配置文件 (profile):"
            echo "  tools           启动管理工具 (phpMyAdmin, Adminer, Redis Commander)"
            echo
            echo "示例:"
            echo "  $0 start        # 启动基本服务"
            echo "  $0 start tools  # 启动所有服务包括管理工具"
            echo "  $0 logs backend # 查看后端服务日志"
            echo "  $0 stop         # 停止所有服务"
            ;;
        *)
            log_error "未知命令: $action"
            echo "使用 '$0 help' 查看帮助信息"
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"